package com.chapter9;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *  https://www.cnblogs.com/lingyejun/p/9744604.html
 */
public class tryResources {

    public InputStream oldTryCatch() {
        // 构建文件对象
        File inputFile = new File("D:\\input.txt");
        // 初始化输入流
        InputStream inputStream = null;
        try {
            // 创建字节输入流
            inputStream = new FileInputStream(inputFile);
            // 读取到1KB字节数组中
            byte[] buffer = new byte[12];
            // 读取数据并放到buffer数组中
            inputStream.read(buffer);
            System.out.println("oldTryCatch读取输出" + new String(buffer));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭流过程，也有可能出现异常
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return inputStream;
    }

    public InputStream tryCatchResources() {
        File file = new File("D:\\input.txt");

        InputStream returnStream = null;

        try (InputStream inputStream = new FileInputStream(file)) {
            byte[] buffer = new byte[12];
            inputStream.read(buffer);
            System.out.println(new String(buffer));
            returnStream = inputStream;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnStream;
    }

    public static void main(String[] args) {
        tryResources t=new tryResources();
        InputStream inputStream = t.tryCatchResources();

        try {
            inputStream.read();
        } catch (IOException e) {
            System.out.println("已经关闭");
        }
    }
}
